﻿<template>
  <div class="app-container">
    <div class="chart-title">档案管理</div>
    <div class="order-list">
      <div
        class="order-items"
        :class="listQuery.type === 1?'active':''"
        @click="stateChange(1)"
      >货品供应商</div>
      <div
        class="order-items"
        :class="listQuery.type === 2?'active':''"
        @click="stateChange(2)"
      >终端供应商</div>
    </div>
    <div class="chart-content">
      <div class="filter-title">
        <el-form label-position="right">
          <el-form-item>
            <el-input
              v-model="listQuery.name"
              style="width: 160px; height:32px;"
              class="filter-item"
              :placeholder="$t('public.name')"
              @keyup.enter.native="handleFilter"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="listQuery.itoc_name"
              style="width: 160px; height:32px;"
              class="filter-item"
              :placeholder="$t('public.itoc')"
              @keyup.enter.native="handleFilter"
            ></el-input>
          </el-form-item>
          <div
            class="search-button"
            @click="handleFilter"
          >
            <img src="@/assets/images/bg_search@2x.png" />
          </div>
          <div
            class="search-button"
            @click="handleRefresh"
          >
            <img src="@/assets/images/bg_reset@2x.png" />
          </div>
        </el-form>
        <div class="filter-right">
          <div
            class="add-button"
            @click="handleCreate"
          >
            <img src="@/assets/images/icon_add@2x.png" />
            <span>新建</span>
          </div>
        </div>
      </div>
      <div class="chart-list">
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255,255,255,0.2)"
          border
          fit
          highlight-current-row
          style="width: 100%min-height:1000px"
        >
          <el-table-column
            fixed="left"
            align="center"
            :label="$t('table.id')"
            width="65"
          >
            <template slot-scope="scope">
              <span>{{
                (listQuery.page - 1) * listQuery.limit + scope.$index + 1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.name')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.itoc')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.itoc_name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.address')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.address }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.linkman')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.linkman }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.mobile')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.linkman_mobile }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('bind.people')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.people_count }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('bind.device')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.equipment_count }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('delivery.company')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.dispatching_name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.creationTime')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.create_time }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('table.actions')"
            fixed="right"
          >
            <template slot-scope="scope">
              <div class="operat-button">
                <div
                  class="read-img"
                  @click="handleRead(scope.row)"
                >
                  <img src="@/assets/images/read@2x.png" />
                </div>
                <div
                  class="read-img"
                  @click="handleModifyStatus(scope.row, 'deleted')"
                >
                  <img src="@/assets/images/delete@2x.png" />
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
      <!-- 编辑 -->
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="right"
          label-width="150px"
          style="width: 400px margin-left:120px"
          size="small"
        >
          <div class="pops">
            <div class="information-title">
              <span class="icon-title"></span>
              <span>基础信息:</span>
            </div>
            <div class="pops-item">
              <div class="pops-left">
                <el-form-item
                  :label="$t('public.name')"
                  prop="name"
                >
                  <el-input
                    v-model="temp.name"
                    :readonly="dialogStatus !== 'create' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('public.itoc') + ' :'"
                  prop="itoc_id"
                >
                  <drop-down-select
                    :data="itocOptions"
                    :count="itocCount"
                    :page-size="pageSize"
                    :disabled="dialogStatus !== 'create' ? true : false"
                    :id="temp.itoc_id"
                    :name="temp.itoc_name"
                    @getList="(pageNumber, search) => {return getItoc(pageNumber, search, 'getItoc');}"
                    @addList="(pageNumber, search) => {return getItoc(pageNumber, search, 'addItoc');}"
                    @choose="data => {return choose(data, 'itoc');}"
                    @remove="remove('itoc')"
                  ></drop-down-select>
                </el-form-item>
                <el-form-item
                  :label="$t('public.address')"
                  prop="address"
                >
                  <el-input
                    v-model="temp.address"
                    :readonly="dialogStatus !== 'create' ? true : false"
                  ></el-input>
                </el-form-item>
              </div>
              <div class="pops-right">
                <el-form-item
                  :label="$t('public.linkman_2') + ' :'"
                  prop="linkman"
                >
                  <el-input
                    v-model="temp.linkman"
                    :readonly="dialogStatus == 'read' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('public.mobile') + ' :'"
                  prop="linkman_mobile"
                >
                  <el-input
                    v-model="temp.linkman_mobile"
                    :readonly="dialogStatus == 'read' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('delivery.company') + ' :'"
                  prop="dispatching_id"
                >
                  <drop-down-select
                    :data="distrOptions"
                    :count="distrCount"
                    :page-size="pageSize"
                    :disabled="dialogStatus == 'read' ? true : false"
                    :id="temp.dispatching_id"
                    :name="temp.dispatching_name"
                    @getList="(pageNumber, search) => {return getDistr(pageNumber, search, 'getDistr');}"
                    @addList="(pageNumber, search) => {return getDistr(pageNumber, search, 'addDistr');}"
                    @choose="data => {return choose(data, 'distr');}"
                    @remove="remove('distr')"
                  ></drop-down-select>
                </el-form-item>
              </div>
            </div>
          </div>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <div>
            <el-button @click="dialogFormVisible = false">{{
              $t("table.cancel")
            }}</el-button>
            <el-button
              type="primary"
              :disabled="!createDisabled"
              @click="createData"
            >{{ $t("table.confirm") }}</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script type="text/javascript">
import dropDownSelect from "@/views/select/dropDownSelect"; // 分页选择控件
import { getToken } from "@/utils/auth"; // get token from cookie
export default {
  name: "IsupplierProfile",
  components: {
    "drop-down-select": dropDownSelect
  },
  data() {
    const validateName = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 20) {
          callback(new Error("名称长度不能大于20个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)[\u4e00-\u9fff\w]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error("名称只能包含汉字、英文、“_”和数字且不为纯数字或纯符号")
            );
          }
        }
      } else {
        callback(new Error("请填写名称"));
      }
    };
    const validateLinkmanMobile = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        var reg = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/; /* 定义验证表达式 */
        if (reg.test(value)) {
          /* 进行验证 */
          callback();
        } else {
          callback(new Error("请输入正确的联系电话"));
        }
      } else {
        callback(new Error("请填写联系电话"));
      }
    };
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      count: [],
      typeOptions: [
        {
          value: 1,
          label: "商品"
        },
        {
          value: 2,
          label: "设备"
        }
      ],
      listQuery: {
        page: 1,
        limit: 20,
        name: "",
        itoc_name: "",
        type: 1
      },
      temp: {
        id: undefined,
        name: "",
        linkman: "",
        linkman_mobile: "",
        dispatching_id: undefined,
        dispatching_name: "",
        itoc_id: undefined,
        itoc_name: "",
        address: ""
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        edit: "编辑",
        create: "添加",
        review: "审核",
        read: "查看"
      },
      rules: {
        name: [{ required: true, trigger: "blur", validator: validateName }],
        itoc_id: [{ required: true, message: "请选择运营中心", trigger: "change" }],
        address: [{ required: true, message: "请填写地址", trigger: "change" }],
        linkman: [{ required: true, message: "请填写联系人", trigger: "change" }],
        linkman_mobile: [{ required: true, trigger: "blur", validator: validateLinkmanMobile }],
        dispatching_id: [{ required: true, message: "请选择配送员", trigger: "change" }]
      },
      createDisabled: true,
      updateDisabled: true,
      areaOptions: [],
      areaCount: undefined,
      itocOptions: [],
      itocCount: undefined,
      distrOptions: [],
      distrCount: undefined,
      pageSize: 20
    };
  },
  created() {
    const token = getToken();
    if (
      token &&
      !this.$store.state.socket.loginTransition &&
      !this.$store.state.socket.loginAccount
    ) {
      this.tokenLogin(token);
    }
    this.getList();
  },
  methods: {
    stateChange(state = '') {
      this.listQuery.type = state;
      this.getList();
    },
    tokenLogin(token) {
      const path = {
        app: "wxadmin",
        api: "api_wxadmin_admin_keepLogin",
        version: "1.0",
        type: 2,
        data: {
          token: token
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        this.socketData(res);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleRefresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        name: "",
        itoc_name: "",
        type: 1
      };
      this.getList();
    },
    // 获取供货商列表
    getList() {
      this.listLoading = true;
      const data = {
        rows: this.listQuery.limit,
        page: this.listQuery.page,
        name: this.listQuery.name ? this.listQuery.name : "",
        itoc_name: this.listQuery.itoc_name ? this.listQuery.itoc_name : "",
        type: this.listQuery.type ? this.listQuery.type : ""
      };
      const path = {
        app: "archives",
        api: "api_archives_supplier_getList",
        version: "1.0",
        data: data
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 打开查看弹窗
    handleRead(row) {
      this.$router.push({
        path: '/base-data/supplier-details',
        query: {
          id: row.id
        }
      })
    },
    handleEdit() {
      this.dialogStatus = "edit";
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: "",
        linkman: "",
        linkman_mobile: "",
        dispatching_id: undefined,
        dispatching_name: "",
        itoc_id: undefined,
        itoc_name: "",
        address: ""
      };
    },
    // 更新数据
    upData() {
      const data = {
        id: this.temp.id ? this.temp.id : "",
        name: this.temp.name ? this.temp.name : "",
        linkman: this.temp.linkman ? this.temp.linkman : "",
        linkman_mobile: this.temp.linkman_mobile ? this.temp.linkman_mobile : "",
        dispatching_id: this.temp.dispatching_id ? this.temp.dispatching_id : "",
        dispatching_name: this.temp.dispatching_name ? this.temp.dispatching_name : "",
        address: this.temp.address ? this.temp.address : "",
        type: this.listQuery.type ? this.listQuery.type : "",
        itoc_id: this.temp.itoc_id ? this.temp.itoc_id : "",
        itoc_name: this.temp.itoc_name ? this.temp.itoc_name : ""
      };
      return data;
    },
    // 添加供货商
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.createDisabled) {
            this.createDisabled = false;
            const data = this.upData();
            const path = {
              app: "archives",
              api: "api_archives_supplier_add",
              version: "1.0",
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(path), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.createDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    handleModifyStatus(row) {
      this.$confirm("此操作将永久删除该供货商信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const path = {
            app: "archives",
            api: "api_archives_supplier_delete",
            version: "1.0",
            data: {
              id: row.id
            }
          };
          this.socketApi.sendSock(JSON.stringify(path), res => {
            if (res) {
              this.socketData(res);
            } else {
              this.$message.error(" 删除失败 ");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 运营中心选择
    getItoc(pageNumber, search, name) {
      const path = {
        app: "common",
        api: "api_archives_itoc_itocList",
        version: "1.0",
        data: {
          rows: this.pageSize,
          page: pageNumber || 1,
          name: search || "",
          returnType: name || ""
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    // 配送公司选择
    getDistr(pageNumber, search, name) {
      const path = {
        app: "archives",
        api: "api_archives_dispatching_getList",
        version: "1.0",
        type: 2,
        data: {
          rows: this.pageSize,
          page: pageNumber || 1,
          name: search || "",
          returnType: name || ""
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    choose(data, name) {
      if (name === "itoc") {
        this.temp.itoc_id = data.id;
        this.temp.itoc_name = data.name;
      } else if (name === "distr") {
        this.temp.dispatching_id = data.id;
        this.temp.dispatching_name = data.name;
      }
      this.calibration("dataForm");
    },
    remove(name) {
      if (name === "itoc") {
        this.temp.itoc_id = undefined;
        this.temp.itoc_name = "";
      } else if (name === "distr") {
        this.temp.dispatching_id = undefined;
        this.temp.dispatching_name = "";
      }
      this.calibration("dataForm");
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "api_wxadmin_admin_keepLogin") {
            this.$store.dispatch("loginTransition", true);
            this.socketApi.sendCache(res => {
              this.socketData(res);
            });
          } else if (resj.api === "api_archives_supplier_getList") {
            this.total = resj.count;
            this.list = resj.data;
            this.listLoading = false;
          } else if (
            resj.api === "api_archives_itoc_itocList" &&
            resj.type === "getItoc"
          ) {
            this.itocOptions = resj.data;
            this.itocCount = resj.count;
          } else if (
            resj.api === "api_archives_itoc_itocList" &&
            resj.type === "addItoc"
          ) {
            this.itocOptions = this.itocOptions.concat(resj.data);
          } else if (resj.api === "api_archives_dispatching_getList" && resj.type === "getDistr") {
            this.distrOptions = resj.data;
            this.distrCount = resj.count;
          } else if (resj.api === "api_archives_dispatching_getList" && resj.type === "addDistr") {
            this.distrOptions = this.distrOptions.concat(resj.data);
          } else if (resj.api === "api_archives_supplier_add") {
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
            this.dialogFormVisible = false;
            this.getList();
          } else if (resj.api === "api_archives_supplier_delete") {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            this.getList();
          }
        }
      }
    },
    calibration(name) {
      this.$refs[name].validate(valid => { });
    }
  }
};
</script>
